﻿/**
 * MouseChaser
 * makes DisplayObjects chase the cursor
 *
 * @author		Allen Chou
 * @version		1.0.0 (last update: Mar 7 2008)
 * @link		http://cjcat2266.deviantart.com
 */

package idv.cjcat.utils.chaser {
	import flash.display.*;
	import flash.events.*;
	import flash.errors.*;
	import flash.utils.*;
	
	public class MouseChaser {
		
		private static var _ratioPair:Array = new Array();
		private static var _timer:Timer = new Timer(1000 / 60);
		
		public function MouseChaser() {
			throw IllegalOperationError("This is a static class; no instantiation is allowed.");
		}
		
		public static function chase(displayObject:DisplayObject, speedRatio:Number = 0.5):void {
			if (speedRatio <= 0) speedRatio = 0.00001;
			if (speedRatio >= 1) speedRatio = 1;
			
			if (_ratioPair.length > 0) {
				for (var i:uint = 0; i < _ratioPair.length; i++) {
					if (_ratioPair[i].obj === displayObject) {
						if (_ratioPair[i].speed == speedRatio) {
							return;
						} else {
							_ratioPair = _ratioPair.splice(i, 1);
							break;
						}
					}
				}
			}
			
			_ratioPair.push( { obj:displayObject, speed:speedRatio } );
			
			if (_ratioPair.length == 1) {
				_timer.start();
				_timer.addEventListener(TimerEvent.TIMER, update);
			}
		}
		
		public static function stop(displayObject:DisplayObject):void {
			if (_ratioPair.length > 0) {
				for (var i:uint = 0; _ratioPair.length > 0; i++) {
					if (_ratioPair[i].obj === displayObject) {
						_ratioPair.splice(i, 1);
						trace(_ratioPair.length);
						if (_ratioPair.length == 0) {
							_timer.stop();
							_timer.removeEventListener(TimerEvent.TIMER, update);
						}
						return;
					}
				}
			}
			
			throw IllegalOperationError("No such DisplayObject, " + displayObject.name + ", has been used by MouseChaser.");
		}
		
		public static function stopAll():void {
			if (_ratioPair.length > 0) {
				for (var i:uint = 0; i < _ratioPair.length; i++) {
					_ratioPair = new Array();
					_timer.stop();
					_timer.removeEventListener(TimerEvent.TIMER, update);
				}
			}
		}
		
		private static function update(e:Event):void {
			for each (var object:Object in _ratioPair) {
				var dx:Number = object.obj.parent.mouseX - object.obj.x;
				var dy:Number = object.obj.parent.mouseY - object.obj.y;
				
				if (Math.pow(dx, 2) + Math.pow(dy, 2) < 1) {
					object.obj.x = object.obj.parent.mouseX;
					object.obj.y = object.obj.parent.mouseY;
					continue;
				}
				
				object.obj.x += object.speed * dx;
				object.obj.y += object.speed * dy;
			}
		}
		
	}
}